//
//  DataPicturesViewController.m
//  MagictoHire
//
//  Created by 锋 on 2017/12/21.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "DataPicturesViewController.h"
#import "BomImgsModel.h"

@interface DataPicturesViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *dataPictureTableView;
@end

@implementation DataPicturesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupFillDataTableView];
    // Do any additional setup after loading the view.
}

- (void)setupUI {
    if (_pictureType == PACKIMAGETYPE) {
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"下载" style:UIBarButtonItemStylePlain target:self action:@selector(onClickDownLoadBtn)];
        [rightBtn setTintColor:[UIColor whiteColor]];
        [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = _pictureType == PACKIMAGETYPE ? @"指定包装" : @"Bom资料";
    self.view.backgroundColor = RGB(242, 242, 242);
}

- (void)setupFillDataTableView {
    _dataPictureTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _dataPictureTableView.delegate = self;
    _dataPictureTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.00001)];
    view.backgroundColor = [UIColor whiteColor];
    _dataPictureTableView.tableHeaderView = view;
    _dataPictureTableView.tableFooterView = view;
    _dataPictureTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_dataPictureTableView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _imageArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_imageArr.count > 0) {
        BomImgsModel *model = _imageArr[indexPath.row];
        UIImage *cachedImg = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.url];
        if (!cachedImg) {
            return 150*displaywidth;
        }
        
        return (cachedImg.size.height/cachedImg.size.width)*(SCREEN_WIDTH-30*displaywidth);
    } else {
        return 120;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    [self confirmCell:cell atIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)confirmCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    BomImgsModel *model = _imageArr[indexPath.row];
    UIImageView *bigImgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, 150*displaywidth) ImageName:@""];
    bigImgView.contentMode = UIViewContentModeScaleAspectFill;
    bigImgView.layer.masksToBounds = YES;
    [cell.contentView addSubview:bigImgView];
    UIImage *cachedImg = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:model.url];
    if (!cachedImg) {
        [self downloadImage:model.url forIndexPath:indexPath];
    }else{
        bigImgView.image  = cachedImg;
        CGFloat height = cachedImg.size.height;
        bigImgView.frame = CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, (height/cachedImg.size.width)*(SCREEN_WIDTH-30*displaywidth));
    }
}

- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL]
                                                          options:2
                                                         progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                                         }
                                                        completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                                            [[SDImageCache sharedImageCache] storeImage:image forKey:imageURL toDisk:YES];
                                                            [weakSelf performSelectorOnMainThread:@selector(reloadCellAtIndexPath:) withObject:indexPath waitUntilDone:NO];
                                                            
                                                        }];
}
- (void)reloadCellAtIndexPath:(NSIndexPath *)indexPath
{
    [_dataPictureTableView reloadData];
}

- (void)onClickDownLoadBtn {
    for (int i = 0; i < _imageArr.count; i++) {
        BomImgsModel *model = _imageArr[i];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.url]]];
        [self saveImageToAlbum:image];
    }
}

//将UIImage保存到本地相册
- (void)saveImageToAlbum:(UIImage *)image{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

//判断是否保存成功
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"图片下载失败";
    if (!error) {
        message = @"图片保下载成功";
    }else{
        message = [error description];
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
